package repository

import (
	"boy-go/modules/system/model"
	"boy-go/modules/system/vo"
	"boy-go/pkg/db"
	"boy-go/pkg/request"
	"gorm.io/gorm"
)

type SysDictTypeRepository struct {
	DB *gorm.DB
}

func NewSysDictTypeRepository() *SysDictTypeRepository {
	return &SysDictTypeRepository{
		DB: db.GetMasterDB(),
	}
}
func (r *SysDictTypeRepository) GetById(dictId int64) (*model.SysDictType, error) {
	db := r.DB
	m := &model.SysDictType{}
	err := db.Model(&model.SysDictType{}).Where("dict_id = ?", dictId).First(m).Error
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (r *SysDictTypeRepository) List(query *vo.QuerySysDictTypeReq, pageReq *request.PageRequest) ([]*model.SysDictType, int64, error) {
	tx := r.DB.Model(&model.SysDictType{})
	if query != nil {
		if query.DictName != nil {
			tx = tx.Where("dict_name = ?", *query.DictName)
		}
		if query.DictType != nil {
			tx = tx.Where("dict_type = ?", *query.DictType)
		}
		if query.Status != nil {
			tx = tx.Where("status = ?", *query.Status)
		}
		if query.Remark != nil {
			tx = tx.Where("remark = ?", *query.Remark)
		}
		if query.Params != nil {
			val, have := query.Params["beginTime"]
			if have {
				beginTime := val.(string)
				tx = tx.Where("date_format(create_time,'%Y%m%d') >= date_format('" + beginTime + "','%Y%m%d')")
			}
			val, have = query.Params["endTime"]
			if have {
				endTime := val.(string)
				tx = tx.Where("date_format(create_time,'%Y%m%d') <= date_format('" + endTime + "','%Y%m%d')")
			}
		}
	}
	list := make([]*model.SysDictType, 0)
	if pageReq != nil {
		offSet := 0
		limit := 10
		if query != nil {
			if pageReq.PageNum > 0 {
				offSet = (pageReq.PageNum - 1) * limit
			}
			if pageReq.PageSize > 0 {
				limit = pageReq.PageSize
			}
		}
		var total int64
		if err := tx.Count(&total).Error; err != nil {
			return nil, 0, err
		}
		if total > 0 {
			if err := tx.Select("*").Offset(offSet).Limit(limit).Find(&list).Error; err != nil {
				return nil, total, err
			}
		}
		return list, total, nil
	} else {
		if err := tx.Select("*").Find(&list).Error; err != nil {
			return nil, 0, err
		}
	}
	return list, int64(len(list)), nil
}

// Save 添加
func (r *SysDictTypeRepository) Save(m *model.SysDictType) error {
	return r.DB.Model(&model.SysDictType{}).Create(m).Error
}

// Update 更新
func (r *SysDictTypeRepository) Update(m *model.SysDictType) error {
	return r.DB.Model(&model.SysDictType{}).Where("dict_id = ?", m.DictId).Omit("dict_id").Updates(m).Error
}

// Delete 删除
func (r *SysDictTypeRepository) Delete(dictId int64) error {
	return r.DB.Model(&model.SysDictType{}).Where("dict_id = ?", dictId).Delete(&model.SysDictType{}).Error
}

// BatchDelete 批量删除
func (r *SysDictTypeRepository) BatchDelete(ids []string) error {
	db := r.DB
	db = db.Where("(dict_id) IN ?", ids)
	return db.Delete(&model.SysDictType{}).Error
}
